class DeviceStatus {
    constructor() {
        this.charts = {};
        
        // 等待 DOM 加载完成后再初始化
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.initialize());
        } else {
            this.initialize();
        }
    }

    initialize() {
        this.initializeCharts();
        this.initializeEventListeners();
        this.updateData();
        this.startRealTimeUpdate();
    }

    initializeCharts() {
        // 初始化参数监控小图表
        const chartConfigs = {
            'pumpFrequencyChart': {
                label: '水泵频率 (Hz)',
                borderColor: '#1890ff'
            },
            'waterFlowChart': {
                label: '出水流量 (m³/h)',
                borderColor: '#52c41a'
            },
            'fertilizerChart': {
                label: '肥料浓度 (%)',
                borderColor: '#faad14'
            },
            'pressureChart': {
                label: '管道压力 (MPa)',
                borderColor: '#ff4d4f'
            }
        };

        Object.entries(chartConfigs).forEach(([chartId, config]) => {
            const ctx = document.getElementById(chartId);
            if (ctx) {
                this.charts[chartId] = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: Array.from({length: 10}, (_, i) => i + 1),
                        datasets: [{
                            label: config.label,
                            data: this.generateMockData(10),
                            borderColor: config.borderColor,
                            borderWidth: 2,
                            pointRadius: 0,
                            tension: 0.4,
                            fill: false
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            }
                        },
                        scales: {
                            x: {
                                display: false
                            },
                            y: {
                                display: false,
                                beginAtZero: true
                            }
                        },
                        animation: false
                    }
                });
            }
        });
    }

    initializeEventListeners() {
        // 刷新按钮点击事件
        const refreshBtn = document.querySelector('.refresh-btn');
        if (refreshBtn) {
            refreshBtn.addEventListener('click', () => {
                // 添加刷新动画效果
                refreshBtn.classList.add('refreshing');
                refreshBtn.querySelector('i').classList.add('fa-spin');
                
                // 更新数据
                this.updateData();
                
                // 1秒后移除刷新动画
                setTimeout(() => {
                    refreshBtn.classList.remove('refreshing');
                    refreshBtn.querySelector('i').classList.remove('fa-spin');
                }, 1000);
            });
        }

        // 告警筛选事件
        document.getElementById('alarm-level-filter').addEventListener('change', () => {
            this.updateAlarmRecords();
        });

        document.getElementById('alarm-status-filter').addEventListener('change', () => {
            this.updateAlarmRecords();
        });

        // 添加维护记录按钮点击事件
        document.querySelector('.add-maintenance-btn').addEventListener('click', () => {
            alert('添加维护记录功能即将上线');
        });
    }

    generateMockData(count, min = 0, max = 100) {
        return Array.from({length: count}, () => min + Math.random() * (max - min));
    }

    updateData() {
        // 更新设备状态
        this.updateDeviceStatus();
        // 更新参数监控
        this.updateParamCharts();
        // 更新告警记录
        this.updateAlarmRecords();
        // 更新维护记录
        this.updateMaintenanceRecords();
    }

    updateDeviceStatus() {
        // 更新水泵状态
        const pumpStatus = Math.random() > 0.8 ? 'warning' : 'normal';
        document.getElementById('pump-status').className = `status-tag ${pumpStatus}`;
        document.getElementById('pump-status').textContent = 
            pumpStatus === 'normal' ? '正常运行' : '需检查';
        document.getElementById('pump-runtime').textContent = 
            Math.floor(Math.random() * 24);

        // 更新混合器状态
        const mixerStatus = Math.random() > 0.7 ? 'warning' : 'normal';
        document.getElementById('mixer-status').className = `status-tag ${mixerStatus}`;
        document.getElementById('mixer-status').textContent = 
            mixerStatus === 'normal' ? '正常运行' : '需维护';
        document.getElementById('mixer-ratio').textContent = 
            `1:${Math.floor(Math.random() * 50 + 80)}`;

        // 更新系统压力
        document.getElementById('system-pressure').textContent = 
            (0.5 + Math.random() * 2.5).toFixed(1);
    }

    updateParamCharts() {
        // 生成新的随机数据
        const newPumpFrequency = (45 + Math.random() * 10).toFixed(1);
        const newWaterFlow = (2 + Math.random() * 2).toFixed(1);
        const newFertilizerConc = (0.8 + Math.random() * 0.8).toFixed(1);
        const newPipePressure = (1.8 + Math.random() * 1).toFixed(1);

        // 更新参数值显示
        const elements = {
            'pump-frequency': newPumpFrequency,
            'water-flow': newWaterFlow,
            'fertilizer-concentration': newFertilizerConc,
            'pipe-pressure': newPipePressure
        };

        // 更新显示的数值
        Object.entries(elements).forEach(([id, value]) => {
            const element = document.getElementById(id);
            if (element) {
                // 添加数值变化的动画效果
                element.style.transition = 'color 0.3s';
                element.style.color = '#1890ff';
                element.textContent = value;
                
                setTimeout(() => {
                    element.style.color = '';
                }, 500);
            }
        });

        // 更新图表数据
        Object.entries(this.charts).forEach(([chartId, chart]) => {
            const data = chart.data.datasets[0].data;
            data.shift(); // 移除第一个数据点
            
            // 根据不同的图表添加相应范围的新数据点
            switch (chartId) {
                case 'pumpFrequencyChart':
                    data.push(parseFloat(newPumpFrequency));
                    break;
                case 'waterFlowChart':
                    data.push(parseFloat(newWaterFlow));
                    break;
                case 'fertilizerChart':
                    data.push(parseFloat(newFertilizerConc));
                    break;
                case 'pressureChart':
                    data.push(parseFloat(newPipePressure));
                    break;
            }
            
            // 更新图表显示
            chart.update('none'); // 使用 'none' 模式以获得更好的性能
        });
    }

    updateAlarmRecords() {
        const tbody = document.getElementById('alarm-records');
        const levelFilter = document.getElementById('alarm-level-filter').value;
        const statusFilter = document.getElementById('alarm-status-filter').value;
        
        const mockData = this.generateMockAlarms(levelFilter, statusFilter);
        
        tbody.innerHTML = mockData.map(record => `
            <tr>
                <td>${record.time}</td>
                <td>${record.device}</td>
                <td>${record.type}</td>
                <td>
                    <span class="status-tag ${record.level.class}">
                        ${record.level.text}
                    </span>
                </td>
                <td>${record.content}</td>
                <td>
                    <span class="status-tag ${record.status.class}">
                        ${record.status.text}
                    </span>
                </td>
                <td>
                    <button class="action-btn" onclick="alert('处理告警功能即将上线')">
                        <i class="fas fa-tools"></i>
                    </button>
                </td>
            </tr>
        `).join('');
    }

    generateMockAlarms(levelFilter, statusFilter) {
        const alarms = [];
        const count = Math.floor(Math.random() * 5) + 3;
        
        const devices = ['水泵', '混合器', '压力阀', '流量计'];
        const types = ['参数异常', '通信中断', '设备故障', '性能下降'];
        
        for (let i = 0; i < count; i++) {
            const level = this.getRandomLevel(levelFilter);
            const status = this.getRandomStatus(statusFilter);
            
            alarms.push({
                time: new Date(Date.now() - Math.random() * 86400000).toLocaleString(),
                device: devices[Math.floor(Math.random() * devices.length)],
                type: types[Math.floor(Math.random() * types.length)],
                level,
                content: this.generateAlarmContent(),
                status
            });
        }
        
        return alarms;
    }

    getRandomLevel(filter) {
        const levels = {
            high: { text: '高级警告', class: 'danger' },
            medium: { text: '中级警告', class: 'warning' },
            low: { text: '低级警告', class: 'normal' }
        };

        if (filter === 'all') {
            const levelKeys = Object.keys(levels);
            return levels[levelKeys[Math.floor(Math.random() * levelKeys.length)]];
        }
        
        return levels[filter] || levels.medium;
    }

    getRandomStatus(filter) {
        const statuses = {
            unprocessed: { text: '未处理', class: 'danger' },
            processing: { text: '处理中', class: 'warning' },
            processed: { text: '已处理', class: 'normal' }
        };

        if (filter === 'all') {
            const statusKeys = Object.keys(statuses);
            return statuses[statusKeys[Math.floor(Math.random() * statusKeys.length)]];
        }
        
        return statuses[filter] || statuses.unprocessed;
    }

    generateAlarmContent() {
        const contents = [
            '设备运行参数超出正常范围',
            '设备通信中断，请检查网络连接',
            '设备运行异常，需要维护',
            '设备性能出现明显下降',
            '设备温度过高，建议检查'
        ];
        
        return contents[Math.floor(Math.random() * contents.length)];
    }

    updateMaintenanceRecords() {
        const tbody = document.getElementById('maintenance-records');
        const mockData = this.generateMockMaintenance();
        
        tbody.innerHTML = mockData.map(record => `
            <tr>
                <td>${record.time}</td>
                <td>${record.device}</td>
                <td>${record.type}</td>
                <td>${record.content}</td>
                <td>${record.staff}</td>
                <td>
                    <span class="status-tag ${record.result.class}">
                        ${record.result.text}
                    </span>
                </td>
                <td>${record.nextTime}</td>
            </tr>
        `).join('');
    }

    generateMockMaintenance() {
        const records = [];
        const count = Math.floor(Math.random() * 3) + 3;
        
        const devices = ['水泵', '混合器', '压力阀', '流量计'];
        const types = ['定期保养', '故障维修', '性能优化', '零件更换'];
        const staff = ['张工', '李工', '王工', '赵工'];
        
        for (let i = 0; i < count; i++) {
            const maintenanceTime = new Date(Date.now() - Math.random() * 604800000);
            const nextTime = new Date(maintenanceTime.getTime() + 2592000000);
            
            records.push({
                time: maintenanceTime.toLocaleDateString(),
                device: devices[Math.floor(Math.random() * devices.length)],
                type: types[Math.floor(Math.random() * types.length)],
                content: this.generateMaintenanceContent(),
                staff: staff[Math.floor(Math.random() * staff.length)],
                result: this.getMaintenanceResult(),
                nextTime: nextTime.toLocaleDateString()
            });
        }
        
        return records;
    }

    generateMaintenanceContent() {
        const contents = [
            '更换滤芯、清洗管道',
            '检查电机、更换轴承',
            '校准参数、系统优化',
            '更换密封圈、紧固螺栓',
            '清理沉淀物、更换管道'
        ];
        
        return contents[Math.floor(Math.random() * contents.length)];
    }

    getMaintenanceResult() {
        const results = [
            { text: '已完成', class: 'normal' },
            { text: '待复检', class: 'warning' },
            { text: '未解决', class: 'danger' }
        ];
        
        return results[Math.floor(Math.random() * results.length)];
    }

    startRealTimeUpdate() {
        // 每30秒更新一次数据
        setInterval(() => {
            this.updateData();
        }, 30000);
    }
}

// 创建实例
window.deviceStatus = new DeviceStatus(); 